<?php
namespace Auth\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Sql;
use Zend\Stdlib\Hydrator\ClassMethods;

class UserMapper
{
    protected $tableName = 'users';
    protected $sql;
    protected $dbAdapter;

    public function __construct(Adapter $dbAdapter)
    {
        $this->dbAdapter = $dbAdapter;
        $this->sql = new Sql($dbAdapter);
        $this->sql->setTable($this->tableName);
    }
    
    public function _isExist( $email )
    {
        $select = $this->sql->select();
        $select->where(array('email' => $email));
        $statement = $this->sql->prepareStatementForSqlObject($select);
        $result = $statement->execute()->current();
        if($result)
            return 1;
        return null;
    }
    

    
    public function addUser(UserEntity $user)
    {
        $hydrator = new ClassMethods();
        $data = $hydrator->extract($user);
        if(empty($data))
            return null;
        $action = $this->sql->insert();
        $action->values($data);
        $statement = $this->sql->prepareStatementForSqlObject($action);
        $result = $statement->execute();
        if(!$user->getId())
            $user->setId($result->getGeneratedValue());
        return $result;
    }
    public function  getUserByEmail($email){
        $hydrator = new ClassMethods();
        $select=$this->sql->select();
        $select->where(array('email'=>$email));
        $statement = $this->sql->prepareStatementForSqlObject($select);
        $result = $statement->execute()->current();
        if($result){
            $user=new UserEntity();
            $hydrator->hydrate($result,$user);
            return $user;
        }
        return null;
    }
   
    
    public function save($userData) {
        $data = ( array ) $userData;
        
        $id = ( int ) $data ['id'];
        if (! $this->userExists ( $data ['email'] ) && $id == 0) {
            $data['created_time'] = date("Y-m-d H:i:s");
            $data['pro_expired_date'] = date("Y-m-d H:i:s");
            $data['modified_time'] = date("Y-m-d H:i:s");
            $data['last_logined'] = date("Y-m-d H:i:s");
            //echo aaa; exit;
            $this->tablegateway->insert ( $data );
            //echo aaa; exit;
            return $this->tablegateway->lastInsertValue;
        } else {
            if ($this->prepareDataForUpdate($data)) {
                $data['modified_time'] = date("Y-m-d H:i:s");
                echo $data ['email'];
                $data['id'] =$this->GetIduserExists ( $data ['email'] );
                $id = $data['id'];
                $this->tablegateway->update ( $data, array("id" => $id) );
                return $id;
            } else {
                throw new \Exception ( 'User does not exist' );
            }
        }
    }
}